/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rie06.openvoip.sound;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author clement
 */
public class AudioRecording extends AudioSpecification implements Runnable {

    private static final Logger logger = Logger.getLogger(AudioRecording.class);
    
    private Thread thread;

    public AudioRecording() {
        super();
        setRecording(true);
        setPause(true);

        if (initRecordingLine()) {
            thread = new Thread(this);
            thread.setName("Ecriture");
            thread.start();
        }
    }

    public void stopConversation() {
        setRecording(false);
    }

    public Thread getThread() {
        return thread;
    }
    
    public void sendSound(int id, byte[] buffer){
        logger.log(Level.ERROR, "Need to implements sendSound");
    }

    @Override
    public void run() {

        System.out.println("Start: Thread(Ecriture.java)");

        //initialize recording line


        // play back the captured audio data
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int frameSizeInBytes = getFormat().getFrameSize();
        byte[] buffer = new byte[getBufSize()];

        getRecordingLine().start();

        int count = 0;
        int i = 0;

        while (isRecording()) {
            
            synchronized (thread) {
                while (isPause()) {
                    logger.log(Level.DEBUG, "Set Recording pause.");
                    try {
                        thread.wait();
                        logger.log(Level.DEBUG, "Set Recording start.");
                    } catch (Exception e) {
                    }
                }
            }
            
            count = getRecordingLine().read(buffer, 0, buffer.length);
            if (count > 0) {
                out.write(buffer, 0, count);
                //System.out.println("Buffer: " + buffer.length + " - Count: " + count);
            }

            //traitement sound
            
            
            //send
            //System.out.println("Send Frame : " + i);
            sendSound(i, buffer.clone());
            i++;
        }
        // we reached the end of the stream.
        // stop and close the line.
        getRecordingLine().stop();
        getRecordingLine().close();
        setRecordingLine(null);

        // stop and close the output stream
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
     
    }
}
